import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import type { ThemeMode, IAsyncState } from '../../types/common/base';

/**
 * 用户偏好设置接口
 * @description 定义用户个性化设置选项
 */
export interface IUserPreferences {
  /** 语言设置 */
  language: 'zh-CN' | 'en-US';
  /** 时间格式 */
  timeFormat: '12h' | '24h';
  /** 日期格式 */
  dateFormat: 'YYYY-MM-DD' | 'MM/DD/YYYY' | 'DD/MM/YYYY';
  /** 每周开始日 */
  weekStartsOn: 0 | 1; // 0: 周日, 1: 周一
  /** 默认课程时长（分钟） */
  defaultCourseDuration: number;
  /** 是否显示周末 */
  showWeekends: boolean;
  /** 是否启用声音提醒 */
  enableSoundNotifications: boolean;
  /** 是否启用桌面通知 */
  enableDesktopNotifications: boolean;
  /** 自动保存间隔（秒） */
  autoSaveInterval: number;
  /** 数据备份频率（天） */
  backupFrequency: number;
}

/**
 * 显示设置接口
 * @description 定义界面显示相关设置
 */
export interface IDisplaySettings {
  /** 课程表视图模式 */
  defaultScheduleView: 'week' | 'day' | 'month';
  /** 是否显示课程颜色 */
  showCourseColors: boolean;
  /** 是否显示教师信息 */
  showTeacherInfo: boolean;
  /** 是否显示地点信息 */
  showLocationInfo: boolean;
  /** 课程卡片大小 */
  courseCardSize: 'small' | 'medium' | 'large';
  /** 是否启用动画效果 */
  enableAnimations: boolean;
  /** 侧边栏默认状态 */
  sidebarCollapsed: boolean;
  /** 表格每页显示数量 */
  tablePageSize: number;
}

/**
 * 应用设置状态接口
 * @description 定义应用设置状态管理的完整接口
 */
export interface ISettingsState {
  // 主题设置
  /** 当前主题模式 */
  themeMode: ThemeMode;
  /** 是否跟随系统主题 */
  followSystemTheme: boolean;
  /** 自定义主题色 */
  customPrimaryColor: string;
  
  // 用户偏好设置
  /** 用户偏好设置 */
  userPreferences: IUserPreferences;
  
  // 显示设置
  /** 显示设置 */
  displaySettings: IDisplaySettings;
  
  // 异步状态
  /** 异步操作状态 */
  async: IAsyncState;
  
  // UI状态
  /** 是否显示设置面板 */
  showSettingsPanel: boolean;
  /** 当前设置面板标签页 */
  activeSettingsTab: 'theme' | 'preferences' | 'display' | 'data';
  /** 是否显示重置确认对话框 */
  showResetConfirm: boolean;
  
  // Actions - 主题相关
  /** 设置主题模式 */
  setThemeMode: (mode: ThemeMode) => void;
  /** 切换主题模式 */
  toggleTheme: () => void;
  /** 设置是否跟随系统主题 */
  setFollowSystemTheme: (follow: boolean) => void;
  /** 设置自定义主题色 */
  setCustomPrimaryColor: (color: string) => void;
  /** 检测系统主题 */
  detectSystemTheme: () => ThemeMode;
  
  // Actions - 用户偏好设置
  /** 更新用户偏好设置 */
  updateUserPreferences: (preferences: Partial<IUserPreferences>) => void;
  /** 重置用户偏好设置 */
  resetUserPreferences: () => void;
  
  // Actions - 显示设置
  /** 更新显示设置 */
  updateDisplaySettings: (settings: Partial<IDisplaySettings>) => void;
  /** 重置显示设置 */
  resetDisplaySettings: () => void;
  
  // Actions - UI操作
  /** 显示设置面板 */
  showSettings: (tab?: ISettingsState['activeSettingsTab']) => void;
  /** 隐藏设置面板 */
  hideSettings: () => void;
  /** 切换设置面板 */
  toggleSettings: () => void;
  /** 设置活跃标签页 */
  setActiveSettingsTab: (tab: ISettingsState['activeSettingsTab']) => void;
  /** 显示重置确认对话框 */
  showResetDialog: () => void;
  /** 隐藏重置确认对话框 */
  hideResetDialog: () => void;
  
  // Actions - 数据操作
  /** 初始化应用 */
  initializeApp: () => Promise<void>;
  /** 导出设置 */
  exportSettings: () => Promise<string>;
  /** 导入设置 */
  importSettings: (settingsData: string) => Promise<void>;
  /** 重置所有设置 */
  resetAllSettings: () => void;
  /** 获取设置摘要 */
  getSettingsSummary: () => {
    theme: string;
    language: string;
    preferences: number;
    lastUpdated: number;
  };
  /** 获取当前主题色 */
  primaryColor: string;
}

/**
 * 默认用户偏好设置
 */
const DEFAULT_USER_PREFERENCES: IUserPreferences = {
  language: 'zh-CN',
  timeFormat: '24h',
  dateFormat: 'YYYY-MM-DD',
  weekStartsOn: 1, // 周一开始
  defaultCourseDuration: 60, // 60分钟
  showWeekends: true,
  enableSoundNotifications: true,
  enableDesktopNotifications: false,
  autoSaveInterval: 30, // 30秒
  backupFrequency: 7 // 7天
};

/**
 * 默认显示设置
 */
const DEFAULT_DISPLAY_SETTINGS: IDisplaySettings = {
  defaultScheduleView: 'week',
  showCourseColors: true,
  showTeacherInfo: true,
  showLocationInfo: true,
  courseCardSize: 'medium',
  enableAnimations: true,
  sidebarCollapsed: false,
  tablePageSize: 10
};

/**
 * 应用设置状态管理
 * @description 管理应用的主题、用户偏好和显示设置
 */
export const useSettingsStore = create<ISettingsState>()(
  devtools(
    persist(
      immer((set, get) => ({
        // 初始状态 - 主题设置
        themeMode: 'auto',
        followSystemTheme: true,
        customPrimaryColor: '#1890ff',
        
        // 初始状态 - 用户偏好设置
        userPreferences: DEFAULT_USER_PREFERENCES,
        
        // 初始状态 - 显示设置
        displaySettings: DEFAULT_DISPLAY_SETTINGS,
        
        // 初始状态 - 异步状态
        async: {
          loading: false,
          error: null,
          lastUpdated: null
        },
        
        // 初始状态 - UI状态
        showSettingsPanel: false,
        activeSettingsTab: 'theme',
        showResetConfirm: false,

        // Actions - 主题相关
        setThemeMode: (mode: ThemeMode) => {
          set((state) => {
            state.themeMode = mode;
            if (mode !== 'auto') {
              state.followSystemTheme = false;
            }
          });
        },

        toggleTheme: () => {
          set((state) => {
            const currentMode = state.themeMode;
            if (currentMode === 'auto') {
              // 如果当前是自动模式，切换到相反的系统主题
              const systemTheme = get().detectSystemTheme();
              state.themeMode = systemTheme === 'dark' ? 'light' : 'dark';
            } else {
              // 在明暗主题间切换
              state.themeMode = currentMode === 'dark' ? 'light' : 'dark';
            }
            state.followSystemTheme = false;
          });
        },

        setFollowSystemTheme: (follow: boolean) => {
          set((state) => {
            state.followSystemTheme = follow;
            if (follow) {
              state.themeMode = 'auto';
            }
          });
        },

        setCustomPrimaryColor: (color: string) => {
          set((state) => {
            state.customPrimaryColor = color;
          });
        },

        detectSystemTheme: (): ThemeMode => {
          if (typeof window !== 'undefined' && window.matchMedia) {
            return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
          }
          return 'light';
        },

        // Actions - 用户偏好设置
        updateUserPreferences: (preferences: Partial<IUserPreferences>) => {
          set((state) => {
            state.userPreferences = { ...state.userPreferences, ...preferences };
            state.async.lastUpdated = Date.now();
          });
        },

        resetUserPreferences: () => {
          set((state) => {
            state.userPreferences = { ...DEFAULT_USER_PREFERENCES };
            state.async.lastUpdated = Date.now();
          });
        },

        // Actions - 显示设置
        updateDisplaySettings: (settings: Partial<IDisplaySettings>) => {
          set((state) => {
            state.displaySettings = { ...state.displaySettings, ...settings };
            state.async.lastUpdated = Date.now();
          });
        },

        resetDisplaySettings: () => {
          set((state) => {
            state.displaySettings = { ...DEFAULT_DISPLAY_SETTINGS };
            state.async.lastUpdated = Date.now();
          });
        },

        // Actions - UI操作
        showSettings: (tab: ISettingsState['activeSettingsTab'] = 'theme') => {
          set((state) => {
            state.showSettingsPanel = true;
            state.activeSettingsTab = tab;
          });
        },

        hideSettings: () => {
          set((state) => {
            state.showSettingsPanel = false;
          });
        },

        toggleSettings: () => {
          set((state) => {
            state.showSettingsPanel = !state.showSettingsPanel;
          });
        },

        setActiveSettingsTab: (tab: ISettingsState['activeSettingsTab']) => {
          set((state) => {
            state.activeSettingsTab = tab;
          });
        },

        showResetDialog: () => {
          set((state) => {
            state.showResetConfirm = true;
          });
        },

        hideResetDialog: () => {
          set((state) => {
            state.showResetConfirm = false;
          });
        },

        // Actions - 数据操作
        initializeApp: async () => {
          try {
            set((state) => {
              state.async.loading = true;
              state.async.error = null;
            });

            // 检测系统主题偏好
            const systemTheme = get().detectSystemTheme();
            
            // 如果设置为跟随系统主题，更新当前主题
            const currentState = get();
            if (currentState.followSystemTheme && currentState.themeMode === 'auto') {
              set((draft) => {
                draft.themeMode = systemTheme;
              });
            }

            // 初始化完成
            set((state) => {
              state.async.loading = false;
              state.async.lastUpdated = Date.now();
            });
          } catch (error) {
            set((state) => {
              state.async.loading = false;
              state.async.error = error instanceof Error ? error.message : '应用初始化失败';
            });
            throw error;
          }
        },

        exportSettings: async () => {
          try {
            set((state) => {
              state.async.loading = true;
              state.async.error = null;
            });

            const state = get();
            const settingsData = {
              version: '1.0.0',
              timestamp: Date.now(),
              settings: {
                themeMode: state.themeMode,
                followSystemTheme: state.followSystemTheme,
                customPrimaryColor: state.customPrimaryColor,
                userPreferences: state.userPreferences,
                displaySettings: state.displaySettings
              }
            };

            const jsonString = JSON.stringify(settingsData, null, 2);

            set((state) => {
              state.async.loading = false;
              state.async.lastUpdated = Date.now();
            });

            return jsonString;
          } catch (error) {
            set((state) => {
              state.async.loading = false;
              state.async.error = error instanceof Error ? error.message : '导出设置失败';
            });
            throw error;
          }
        },

        importSettings: async (settingsData: string) => {
          try {
            set((state) => {
              state.async.loading = true;
              state.async.error = null;
            });

            const parsedData = JSON.parse(settingsData);
            
            // 验证数据格式
            if (!parsedData.settings) {
              throw new Error('无效的设置数据格式');
            }

            const { settings } = parsedData;

            set((state) => {
              // 导入主题设置
              if (settings.themeMode) {
                state.themeMode = settings.themeMode;
              }
              if (typeof settings.followSystemTheme === 'boolean') {
                state.followSystemTheme = settings.followSystemTheme;
              }
              if (settings.customPrimaryColor) {
                state.customPrimaryColor = settings.customPrimaryColor;
              }

              // 导入用户偏好设置
              if (settings.userPreferences) {
                state.userPreferences = { ...state.userPreferences, ...settings.userPreferences };
              }

              // 导入显示设置
              if (settings.displaySettings) {
                state.displaySettings = { ...state.displaySettings, ...settings.displaySettings };
              }

              state.async.loading = false;
              state.async.lastUpdated = Date.now();
            });
          } catch (error) {
            set((state) => {
              state.async.loading = false;
              state.async.error = error instanceof Error ? error.message : '导入设置失败';
            });
            throw error;
          }
        },

        resetAllSettings: () => {
          set((state) => {
            state.themeMode = 'auto';
            state.followSystemTheme = true;
            state.customPrimaryColor = '#1890ff';
            state.userPreferences = { ...DEFAULT_USER_PREFERENCES };
            state.displaySettings = { ...DEFAULT_DISPLAY_SETTINGS };
            state.async.lastUpdated = Date.now();
            state.showResetConfirm = false;
          });
        },

        getSettingsSummary: () => {
          const state = get();
          return {
            theme: state.themeMode === 'auto' ? '跟随系统' : state.themeMode === 'dark' ? '深色模式' : '浅色模式',
            language: state.userPreferences.language === 'zh-CN' ? '中文' : 'English',
            preferences: Object.keys(state.userPreferences).length + Object.keys(state.displaySettings).length,
            lastUpdated: state.async.lastUpdated || Date.now()
          };
        },

        // 计算属性
        get primaryColor() {
          return get().customPrimaryColor;
        }
      })),
      {
        name: 'settings-store',
        partialize: (state) => ({
          themeMode: state.themeMode,
          followSystemTheme: state.followSystemTheme,
          customPrimaryColor: state.customPrimaryColor,
          userPreferences: state.userPreferences,
          displaySettings: state.displaySettings
        })
      }
    ),
    {
      name: 'settings-store'
    }
  )
);